package com.example.demo.advice;

import cn.hutool.core.util.IdUtil;
import com.example.demo.core.exception.BizException;
import com.example.demo.core.response.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionAdvice {

    @ExceptionHandler(value = Exception.class)
    public ApiResponse<Object> Exception(Exception e) {
        String errorId = IdUtil.simpleUUID();
        log.error("系统异常：{}", errorId, e);
        return ApiResponse.fail("系统异常：" + errorId);
    }

    @ExceptionHandler(value = BizException.class)
    public ApiResponse<Object> BizException(BizException e) {
        return ApiResponse.fail(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ApiResponse<Object> MethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult exceptions = e.getBindingResult();
        if (exceptions.hasErrors()) {
            List<ObjectError> errors = exceptions.getAllErrors();
            if (!errors.isEmpty()) {
                FieldError fieldError = (FieldError) errors.get(0);
                return ApiResponse.fail(fieldError.getDefaultMessage());
            }
        }
        return ApiResponse.fail("参数验证失败");
    }
}
